<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\admin\controller\user;

use addons\epay\library\Service;
use app\common\controller\Backend;
use app\common\library\WechatPay;
use app\common\manager\BaseManager;
use app\common\manager\PayLogManager;
use app\common\manager\prepay\PrepayManager;
use app\common\manager\UserAccountManager;
use app\common\manager\WithdrawManager;
use app\common\model\Transferrecord;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use WeChatPay\Builder;

/**
 * 提现表记录
 *
 * @icon fa fa-circle-o
 */
class Withdrawrecord extends Backend
{

    /**
     * Withdrawrecord模型对象
     * @var \app\admin\model\user\Withdrawrecord
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Withdrawrecord;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("reviewStatusList", $this->model->getReviewStatusList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $userId = $this->request->param("ids");
        $uid = $this->request->param("uid");
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where(function ($query) use ($uid) {
                        if ($uid){
                            return $query->where('user_id',$uid);
                        }
                    })
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('userId', $userId);
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['review_status'] == \app\admin\model\user\Withdrawrecord::REVIEW_STATUS_SUCCESS) {
                $user = \app\common\model\User::where('id', $row->user_id)->find();
                if (!$user->open_id){
                    throw new Exception('当前用户未授权微信小程序，无法转账');
                }
                $orderId = orderNum();
                $post = [
                    'relationType'=>'Transfer',
                    'out_batch_no'=>$orderId,
                    'batch_name'=>date('Y年m月d日',time()).'用户分佣',
                    'batch_remark'=>date('Y年m月d日',time()).'用户分佣',
                    'total_amount'=>intval(bcmul($row->amount,100)),
                    'total_num'=>1,
                    'transfer_detail_list'=>[[
                        'out_detail_no'=>$orderId,
                        'transfer_amount'=>intval(bcmul($row->amount,100)),
                        'transfer_remark'=>date('Y年m月d日',time()).'用户分佣',
                        'openid'=> $user->open_id,
                        'user_id'=> $user->id,
                        'relation_id'=> $row->id,
                        'relation_order'=> $row->order,
                    ]]
                ];
                PrepayManager::order($user,$post,false);
                $result = PrepayManager::getResult();
                if (isset($result['code']) && $result['code']!=BaseManager::$successCode){
                    $this->error($result['message']);
                }
            }else if ($params['review_status']==\app\admin\model\user\Withdrawrecord::REVIEW_STATUS_REJECT){
                $params['status'] = \app\admin\model\user\Withdrawrecord::STATUS_BACK;
                $resultUserAccount = UserAccountManager::money($row->user_id,$row->amount,0,time(),UserAccountManager::TYPE_FREEZE_RETURN,['relation_id'=>$row->id,'relation_order'=>$row->order],false);
                if ($resultUserAccount['code']!=UserAccountManager::$successCode){
                    throw new Exception($resultUserAccount['message']);
                }
            }
            $adminInfo = $this->auth->getUserInfo();
            $params['reviewer'] = $adminInfo['id'];
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
